//实现阻塞队列案例
//先进先出
class BlockQueue{
    private static String[] elems = null;//先设置一个空数组
    private static int head;//头
    private static int fail;//尾
    private static int size;//记录当前数组实际长度
    //入队
    public BlockQueue(int number){
        elems = new String[number];
    }
    public void put(String elem) throws InterruptedException {
        synchronized (this){
            if(size>=elems.length){
                //队列满了
                this.wait();
            }
            elems[fail] = elem;
            size++;
            fail++;
            if(fail>=elems.length){
                //代表数组已经全部满了
                fail=0;
            }
            this.notify();
        }
    }
    public String take() throws InterruptedException {
        synchronized (this){
            if (size==0){
                //队列里面没有东西
                this.wait();
            }
            String result = elems[head];
            head++;
            if(head>=elems.length){
                head=0;
            }
            size--;
            this.notify();
            return result;
        }
    }
}

public class Homework {
    public static void main(String[] args) {
        BlockQueue queue = new BlockQueue(1000);
        Thread t1 = new Thread(()->{
            try {
                int count = 1;
                while (true){
                    queue.put(count+"");
                    count++;
                }
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        });
        Thread t2 = new Thread(()->{
            try {
                while (true){
                    String result = queue.take();
                    System.out.println("count = "+result);
                    Thread.sleep(1000);
                }
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        });
        t1.start();
        t2.start();
    }
}
